package org.dromara.one.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.dromara.common.excel.convert.ExcelBigNumberConvert;

import java.util.LinkedList;
import java.util.List;

@Slf4j
public class EasyExcelUtils {
    /**
     * excel内容样式
     *
     * @return
     */
    public static WriteCellStyle getContentStyle() {
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //垂直居中,水平居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        //设置 自动换行
        //contentWriteCellStyle.setWrapped(true);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 14);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        return contentWriteCellStyle;
    }
    /**
     * 表格頭部樣式
     *
     * @return
     */
    public static WriteCellStyle getHeadStyle() {
        WriteCellStyle headStyle = new WriteCellStyle();
        headStyle.setWrapped(false);
        return headStyle;
    }


    /**动态头传入*/
    public static List<List<String>> head(String[] header, String bigTitle) {
        List<String> head0 = null;
        List<List<String>> list = new LinkedList<List<String>>();
        for (String h : header) {
            head0 = new LinkedList<>();
            head0.add(bigTitle);
            head0.add(h);
            list.add(head0);
        }
        return list;
    }


    /**
     * @Author Zhongks
     * @Description //TODO 合并sheet
     * @Date 10:39 2021/5/11
     * @Param [targetWorkbook, sourceWorkbook]
     * @return org.apache.poi.ss.usermodel.Workbook
     **/
    public static Workbook mergeWorkSheet(Workbook targetWorkbook, Workbook sourceWorkbook, int size, String sheetName){
        try{
            Sheet targetSheet = targetWorkbook.createSheet(sheetName);

            int sheetSize = 0;

            for(int i=0;i<size;i++){
                Sheet firstSourceSheet=sourceWorkbook.getSheetAt(i);
                //获得第一个sheet总行数
                int firstSourceSheetLen=firstSourceSheet.getPhysicalNumberOfRows();
                //            得到需要合并单元格的坐标列表，row与col都从0开始计算
                List<CellRangeAddressExcelVo> cellRangeAddressExcelVoList = getCellRangeAddressExcelVoList(sheetSize,
                        sheetSize+firstSourceSheetLen,
                        firstSourceSheet);
                POIUtil.copySheet(targetSheet, firstSourceSheet, targetWorkbook, sourceWorkbook,sheetSize,cellRangeAddressExcelVoList);
                sheetSize += (firstSourceSheetLen+1);
            }
            return targetWorkbook;
        }catch (Exception e){
            log.error("Workbook合并出错",e);
            return null;
        }
    }



    /**
     * @Author Zhongks
     * @Description //TODO 根据表格场景自定义需要返回合并的单元格位置坐标（注意：row与col都从0开始计算）
     * @Date 14:23 2021/5/11
     * @Param [row, col]
     * @return java.util.List<com.cdtye.itps.jjxt.model.excel.CellRangeAddressExcelVo>
     **/
    public static List<CellRangeAddressExcelVo> getCellRangeAddressExcelVoList(int row,int col,Sheet sheet){
        //合并单元格坐标位置
        List<CellRangeAddressExcelVo> list=new LinkedList<>();
        Row rowTemp = null;
        for(int i=0;i<sheet.getPhysicalNumberOfRows();i++){
            Row row1 = sheet.getRow(i);
            if(rowTemp!=null){
                row1.getCell(0).setCellType(CellType.STRING);
                if(row1.getCell(0).getStringCellValue().equals(rowTemp.getCell(0).getStringCellValue())){
                    fillStrategyMap(list, row+i);
                }
            }
            rowTemp = row1;
        }
        return list;
    }

    private static void fillStrategyMap( List<CellRangeAddressExcelVo> rowRangeDtoList, int index) {
        boolean flag = false;
        for (CellRangeAddressExcelVo dto : rowRangeDtoList) {
            //分段list中是否有end索引是上一行索引的，如果有，则索引+1
            if (dto.getLastRow() == index-1) {
                dto.setLastRow(index);
                flag = true;
            }
        }
        //如果没有，则新增分段
        if (!flag) {
            rowRangeDtoList.add(new CellRangeAddressExcelVo(index-1,index,0,0));
        }
    }




    public static void writerSheet(ExcelWriter excelWriter,int sheetNo,String sheetName,Class className,List<?> list ){
        WriteSheet writeSheet = null;
        try{
             writeSheet = EasyExcel.writerSheet(sheetNo, sheetName)
                    //设置表单头部信息
                    .head(className)
                     .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                     // 大数值自动转换 防止失真
                     .registerConverter(new ExcelBigNumberConvert())
                    //设置拦截器和自定义样式
//                    .registerWriteHandler(new HorizontalCellStyleStrategy(EasyExcelUtils.getHeadStyle(), EasyExcelUtils.getContentStyle()))
                    //设置样式及写入表单头信息开始的行数
                    .useDefaultStyle(true)
                    .build();
            excelWriter.write(list, writeSheet);
        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }


    }
}

